<template>
  <div class="header">
    <div class="inner">
      <div class="title">提问标注工具</div>
      <div class="tools">
        <input
          type="file"
          ref="fileSelectRef"
          v-show="false"
          accept=".json"
          @change="onChange"
        />
        <span style="color: #f56c6c">
          请先下载保存现有标注结果，否则新打开文件会覆盖掉现有标注结果
        </span>
        <el-button type="primary" @click="onSelect"> 打开 </el-button>
        <el-button type="success" @click="onDownload"> 下载 </el-button>
        <el-button type="warning" @click="onCheck"> 审核 </el-button>
      </div>
    </div>
    <el-divider style="margin: 0" />
  </div>
</template>

<script setup lang="ts">
import piniaStore from "@/store";
import {
  IContext,
  IJsonData,
  IJsonDataContext,
  IJsonItem,
} from "@/types/question";
import { ElMessage, ElMessageBox } from "element-plus";
import { ref } from "vue";
import { useRouter } from "vue-router";

interface EmitType {
  (e: "success", value: IJsonData): void;
}
const emit = defineEmits<EmitType>();

const fileSelectRef = ref<HTMLInputElement>();
const onSelect = async () => {
  if (piniaStore.questionStore.currentFileName) {
    await ElMessageBox.confirm("请注意保存当前数据?", "提示", {
      confirmButtonText: "已保存",
      cancelButtonText: "去保存",
      type: "warning",
    });
  }
  fileSelectRef.value?.click();
};

const isJSON = (str: string) => {
  if (typeof str !== "string") {
    return false;
  }

  try {
    const obj = JSON.parse(str);
    if (typeof obj === "object" && obj) {
      return true;
    } else {
      return false;
    }
  } catch (e) {
    return false;
  }
};
const onChange = () => {
  const file = fileSelectRef.value?.files;
  if (!file?.length) return;
  const reader = new FileReader();
  reader.onload = function () {
    const content = reader.result as string;
    if (isJSON(content)) {
      const parseContent: IJsonItem[] = JSON.parse(content);
      // debugger
      const contexts: IContext[] = [];
      parseContent.forEach((content) => {
        if (
          !contexts.find((e) => e.context_id === content.context.context_id)
        ) {
          contexts.push(content.context);
        }
      });
      const json: IJsonDataContext[] = contexts.map((item) => {
        return {
          context_id: item.context_id,
          context: item.context,
          qaList: parseContent
            .filter((e) => e.context.context_id === item.context_id)
            .map((e) => {
              return {
                question: e.question,
                answer: e.answer,
                question_type: e.question_type,
              };
            }),
        };
      });
      emit("success", {
        fileName: file[0].name,
        contexts: json,
      });
      fileSelectRef.value!.value = "";
    } else {
      ElMessage.error("读取失败");
    }
  };
  reader.readAsText(file[0], "UTF-8");
};

const onDownload = async () => {
  await ElMessageBox.confirm("下载，是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  });
  const json = piniaStore.questionStore.json;
  const result: IJsonItem[] = [];
  json.forEach((item) => {
    item.qaList.forEach((qa) => {
      result.push({
        id: 0,
        question: qa.question,
        question_type: qa.question_type,
        answer: qa.answer,
        context: {
          context_id: item.context_id,
          context: item.context,
        },
      });
    });
  });
  result.forEach((item, index) => (item.id = index + 1));
  const blob = new Blob([JSON.stringify(result)]);
  const downloadElement = document.createElement("a");
  const href = window.URL.createObjectURL(blob);
  downloadElement.href = href;
  downloadElement.download = `${
    piniaStore.questionStore.currentFileName.split(".")[0]
  }_question.json`;
  document.body.appendChild(downloadElement);
  downloadElement.click();
  document.body.removeChild(downloadElement);
  window.URL.revokeObjectURL(href);
  // const json = piniaStore.questionStore.json
  // const question = piniaStore.questionStore.questions.find(item => item.fileName === piniaStore.questionStore.currentFileName)?.questions || {}
  // const result = json.map(item => {
  //   return {
  //     ...item,
  //     question_list: question[item.id] || []
  //   }
  // })
  // const blob = new Blob([JSON.stringify(result)])
  // const downloadElement = document.createElement('a')
  // const href = window.URL.createObjectURL(blob)
  // downloadElement.href = href
  // downloadElement.download = `${piniaStore.questionStore.currentFileName.split('.')[0]}_question.json`
  // document.body.appendChild(downloadElement)
  // downloadElement.click()
  // document.body.removeChild(downloadElement)
  // window.URL.revokeObjectURL(href)
};

const router = useRouter();
const onCheck = () => {
  router.push("/home/check");
};
</script>

<style scoped lang="scss">
.header {
  width: 100%;
  height: 60px;
  font-size: 28px;
  text-align: center;
  line-height: 60px;
  .tools {
    height: 60px;
  }

  .inner {
    width: 1300px;
    margin: 0 auto;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 10px;
    span {
      font-size: 14px;
      margin-right: 20px;
    }
  }
}
</style>
